package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"novel/cache"
	"novel/models"
)

type ReadController struct {
	beego.Controller
}

func (c *ReadController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	var count int64
	models.DB.Model(&models.Book{}).Count(&count)
	offset := (page - 1) * size
	get, _ := cache.Rdb.Get(cache.Ctx, "redis_list").Result()
	var rea []models.ReadData
	if get == "" {
		models.DB.Debug().
			Model(&models.Read{}).
			Offset(offset).Limit(size).
			Select("`reads`.*, books.title,books.name,books.contest,books.img").
			Joins("join `books` on `reads`.book_id = books.id").
			Find(&rea)
		JsonData, _ := json.Marshal(rea)
		cache.Rdb.Set(cache.Ctx, "redis_list", JsonData, 0)
	} else {
		json.Unmarshal([]byte(get), &rea)
	}
	c.Data["json"] = map[string]interface{}{
		"code":  200,
		"msg":   "查询成功",
		"data":  rea,
		"page":  page,
		"size":  size,
		"count": count,
	}
	c.ServeJSON()
	return
}
